import { ref } from "vue";
import { cloneDeep } from "lodash-es";

export function useTable(options = {}) {
  /**
   * @param {Object} options - 配置选项
   * @param {Function} options.getPages - 获取分页数据的函数
   * @param {Function} [options.beforeQuery] - 查询前的钩子函数，用于修改查询参数
   * @param {Function} [options.afterQuery] - 查询后的钩子函数，用于处理查询结果
   * @param {Object} [options.customPagination] - 自定义分页配置
   * @param {number} [options.customPagination.page] - 当前页码
   * @param {number} [options.customPagination.pageSize] - 每页条数
   * @param {number[]} [options.customPagination.pageSizes] - 每页条数选项
   * @param {number} [options.customPagination.total] - 总条数
   * @param {string} [options.customPagination.layout] - 分页布局
   * @param {boolean} [options.customPagination.autoAmend] - 是否自动修正页码
   */
  const { getPages, beforeQuery, afterQuery, customPagination } = options;

  const defaultPagination = {
    page: 1,
    pageSize: 10,
    pageSizes: [10, 20, 30, 40],
    total: 0,
    layout: "total, prev, pager, next, sizes, jumper",
    // style: { margin: "0 0 0 auto" },
    autoAmend: false,
  };

  // 合并默认配置和自定义配置
  const mergedPagination = {
    ...defaultPagination,
    ...customPagination,
  };

  // 确保 pageSize 按数字大小插入到 pageSizes 中
  if (!mergedPagination.pageSizes.includes(mergedPagination.pageSize)) {
    const insertIndex = mergedPagination.pageSizes.findIndex(
      (size) => size > mergedPagination.pageSize,
    );
    mergedPagination.pageSizes.splice(
      insertIndex === -1 ? mergedPagination.pageSizes.length : insertIndex,
      0,
      mergedPagination.pageSize,
    );
  }

  const selections = ref([]);
  const tableRef = ref(null);
  const current = ref(null);
  const loading = ref(false);
  const datasourceData = ref([]);
  const editableData = ref([]);
  const pagination = ref(mergedPagination);

  const datasource = async ({ page, limit, where, orders, filters }) => {
    try {
      loading.value = true;
      console.log("查询参数:", { page, limit, where, orders });
      // 构建基础查询参数
      let queryParams = { page, limit, ...where, ...orders, ...filters };

      pagination.value = {
        ...pagination.value,
        page,
        pageSize: limit,
        total: 0, // 初始时设置为0，后续会根据实际数据更新
      };
      // 保存查询参数到tableRef
      if (tableRef.value) {
        tableRef.value.queryParams = {
          ...(tableRef.value.queryParams || {}),
          where,
          orders,
          filters,
        };
      }
      // 执行beforeQuery钩子，允许修改查询参数
      if (beforeQuery) {
        const modifiedParams = await beforeQuery(queryParams);
        if (modifiedParams === false) return; // 取消查询
        queryParams = modifiedParams || queryParams;
      }
      // 执行查询操作，等待结果返回，添加loadin
      const result = await getPages(queryParams);

      datasourceData.value = result.data || [];
      console.log("result", result);
      pagination.value = {
        ...pagination.value,
        page,
        pageSize: limit,
        total: result.count || 0,
      };

      // 查询后钩子
      if (afterQuery) {
        const modifiedResult = await Promise.resolve(afterQuery(result));
        if (modifiedResult) {
          datasourceData.value = modifiedResult;
          return modifiedResult;
        }
      }
      return result;
    } catch (error) {
      console.error("查询失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  const reload = (where = {}, page = pagination.value.page) => {
    // 清空选中项
    selections.value = [];
    const queryParams = tableRef.value?.queryParams || {};
    return tableRef.value.reload({
      page,
      where: {
        ...(queryParams.where || {}),
        ...where,
      },
    });
  };

  const editColumns = (index) => {
    editableData.value[index] = cloneDeep(datasourceData.value[index]);
  };

  const dblClickEdit = (record, index) => {
    return {
      onDblclick: () => {
        current.value = record;
        editColumns(index);
      },
    };
  };

  /** 展开全部 */
  const expandAll = () => {
    tableRef.value?.toggleRowExpansionAll?.(true);
  };

  /** 折叠全部 */
  const foldAll = () => {
    tableRef.value?.toggleRowExpansionAll?.(false);
  };

  return {
    loading,
    pagination,
    datasource,
    reload,
    editColumns,
    dblClickEdit,
    expandAll,
    foldAll,
    current,
    datasourceData,
    editableData,
    selections,
    tableRef,
  };
}
